#include "CCSkeleton.h"
#include "CCSpineGlobal.h"

NS_CC_BEGIN

CCSkeleton::CCSkeleton() {
}

CCSkeleton::~CCSkeleton() {
	for(auto it: m_boneMap) {
		it.second->release();
	}
    
    for(auto it: m_slotDisplayList) {
		it->release();
	}
    
    for(auto it: m_skinMap) {
		it.second->release();
	}
    
    for(auto it: m_animMap) {
		it.second->release();
	}
}

CCSkeleton* CCSkeleton::create() {
	CCSkeleton* s = new CCSkeleton();
	return (CCSkeleton*)s->autorelease();
}

void CCSkeleton::addBone(CCBone* bone) {
    bone->retain();
	m_boneMap.insert(make_pair(bone->getName(), bone));
}

void CCSkeleton::addSlot(CCSlot* slot) {
    slot->retain();
    m_slotMap.insert(make_pair(slot->getName(), slot));
    m_slotDisplayList.push_back(slot);
}

void CCSkeleton::addSkin(CCSkin* skin) {
    skin->retain();
    m_skinMap.insert(make_pair(skin->getName(), skin));
}

void CCSkeleton::addAnim(cocos2d::CCSkeletalAnimation *anim) {
    anim->retain();
    m_animMap.insert(make_pair(anim->getName(), anim));
}

CCBone* CCSkeleton::getRootBone() {
	if(m_boneMap.size())
	{
		CCBone* bone=m_boneMap.begin()->second;
		while(bone->getParent()!=NULL) {
			bone=bone->getParent();
		}
		return bone;
	}
	return NULL;
}

CCBone* CCSkeleton::getBone(const char* name) {
	if(!name) {
	   return NULL;
	}
	BoneMap::iterator iter = m_boneMap.find(name);
	if(iter != m_boneMap.end()) {
		return iter->second;
	} else {
		return NULL;
	}
}

CCSlot* CCSkeleton::getSlot(const char* name) {
	if(!name) {
		return NULL;
	}
	SlotMap::iterator iter = m_slotMap.find(name);
	if(iter != m_slotMap.end()) {
		return iter->second;
	} else {
		return NULL;
	}
}

CCSkin* CCSkeleton::getSkin(const char* name) {
    if(!name) {
		return NULL;
    }
	SkinMap::iterator iter = m_skinMap.find(name);
	if(iter != m_skinMap.end()) {
		return iter->second;
	} else {
		return NULL;
	}
}

CCSkeletalAnimation* CCSkeleton::getAnim(const char *name) {
    if (!name) {
        return NULL;
    }
    AnimationMap::iterator iter=m_animMap.find(name);
    if (iter!=m_animMap.end()) {
        return iter->second;
    }
    else {
        return NULL;
    }
}

NS_CC_END